<?php

include_once('gcal_events_display.php');

class SidebarEventsDisplay extends gcalEventsDisplay
{

    function displayEvents ($xml, $maxEvents, $calID)
	{
		$eventCount = 0;

		$latestDate = NULL;
		
		echo '<div id="gcal-events-list">';
		foreach($xml->entry as $entry)
		{
			$eventCount++;
			if ($eventCount > $maxEvents)
			{
				break;
			}
			$gd = $entry->children('http://schemas.google.com/g/2005');
			
			$start = new DateTime ($gd->when->attributes()->startTime);
			$end = new DateTime ($gd->when->attributes()->endTime);
			$date = $start->format ('D j M Y');
			$startTime = $start->format ('g:i a');
			$endTime = $end->format ('g:i a');
			$where = $gd->where->attributes()->valueString;
		
	
			if (is_null($latestDate) || $start->diff ($latestDate)->days > 0)
			{
				if ($eventCount > 1)
				{
					echo "<br/>";
				}
				echo '<span class="gcal-events-date">' . $date . '</span><br/>';
			}

			// ?? temporary fudge cos details pages not currently working properly
//			if (1 == 2)
			if (strlen((string) $entry->content) > 0)
			{
				// build a URL for a page containing the event's details
				
				// ?? need to get the last path element from something like
				// http://www.google.com/calendar/feeds/j3695eh660ak6p0tn349hukmdo%40group.calendar.google.com/public/full/va2582ia9vkcv4qu8r2qb161go
				$eventURL = $entry->id;
			
				// get the path from the event ID url
				$eventPath = parse_url ($eventURL, PHP_URL_PATH);
				$eventPathComponents = explode ('/', $eventPath);
			
				// event id is the last component
				$eventID = $eventPathComponents [count($eventPathComponents) - 1];
			
				// maybe have a check here to see that there is some content to display on a page. Don't make it a link if not
				$eventPageURL = add_query_arg( array('cal' => urlencode($calID), 'event' => urlencode($eventID)), site_url('gcal_event') );
//				$eventPageURL = add_query_arg( array('cal' => $calID, 'event' => $eventID), site_url() );
//				$eventPageURL = add_query_arg( array('plugin_page' => 'gcal_event', 'cal' => $calID, 'event' => $eventID), site_url() );
			
				echo '<span class="gcal-events-time">' . 
			     	$startTime . 
			     	'</span> <span class="gcal-events-title">' . 
			     	'<a href="' . $eventPageURL . '">' .
			     	(string)$entry->title;
			
				if (strlen ($where) > 0)
				{
					echo ' @ ' . $where;
				} 
			
				echo '</a></span><br/>';
			}
			else
			{
				// no details to display, so no link needed
				echo '<span class="gcal-events-time">' . 
			     	$startTime . 
			     	'</span> <span class="gcal-events-title">' . 
			     	(string)$entry->title;
			
				if (strlen ($where) > 0)
				{
					echo ' @ ' . $where;
				} 
			
				echo '</span><br/>';
			}
			
			$latestDate = $start;
		}
		echo '</div>';
	}

}
?>